package com.ly.work.zk;


import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//读写锁
public class CacheTest {

    //初始化map集合
    public static Map<String,Object> map = new HashMap<String,Object>(){
        {
            put("a","a");
            put("b","b");
            put("c","c");
            put("d","d");
        }
    };

    //声明读写锁
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readlock = reentrantReadWriteLock.readLock();
    private static Lock writelock = reentrantReadWriteLock.writeLock();

    public static void main(String[] args) {
        //声明读写线程集合
        List<Thread> readlist = new ArrayList<Thread>();
        List<Thread> writelist = new ArrayList<Thread>();

        for (int i = 0; i < 1000 ; i++){
            //读线程
            Thread readthread = new Thread(() -> {
                try {
                    //加锁
                    readlock.lock();
                    System.out.println(Thread.currentThread().getName() + "正在读取数据,数据内容为:" + JSON.toJSONString(map));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //释放锁
                    readlock.unlock();
                }
            });
            //将读线程加入集合
            readlist.add(readthread);


            //写线程
            Thread writethread = new Thread(() -> {
                try {
                    //加锁
                    writelock.lock();
                    System.out.println(Thread.currentThread().getName() + "正在更新数据...");
                    //更新map数据
                    map.put("a", Thread.currentThread().getName() + "==a");
                    map.put("b", Thread.currentThread().getName() + "==b");
                    map.put("c", Thread.currentThread().getName() + "==c");
                    map.put("d", Thread.currentThread().getName() + "==d");
                    //输出结果
                    System.out.println(Thread.currentThread().getName() + "数据更新完成,结果为:" + JSON.toJSONString(map));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //释放锁
                    writelock.unlock();
                }
            });
            //将写线程加入集合
            writelist.add(writethread);
        }

        //执行线程
        for (int i = 0; i< writelist.size() ; i++){
            readlist.get(i).start();
            writelist.get(i).start();
        }
    }
}
